package com.kehao.account_book.service;

import com.kehao.account_book.pojo.ClientExpenditure;
import com.kehao.account_book.pojo.Expenditure;
import com.kehao.account_book.repository.ExpenditureRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kehao
 * @date 2020/2/22-16:12
 */
@Service
public class ExpenditureService {
    @Autowired
    private ExpenditureRepository repository;

    @Transactional
    public void updateExpenditure(ClientExpenditure ce,int modify){
        //可能修改是在本地离线情况下创建了，又经过了修改 ，先判断是否存在，存在则update 否则添加
        List<Expenditure> list =  repository.findByUsernameAndYearAndMonthAndDayAndHourAndMinAndSecond(
                ce.getUsername(),ce.getYear(),ce.getMonth(),ce.getDay(),ce.getHour(),ce.getMin(),ce.getSecond());
       // 若存在列表里应该只有一个，否则没有
        if(list.size()==0){
            addExpenditure(ce,modify);
        }else {
            if(ce.getAnchor() == list.get(0).getModify()){
                repository.updateExpenditureById(ce.getType(),ce.getMoney(),ce.getComment(),modify,list.get(0).getId());
            }
        }
    }

    public void addExpenditure(ClientExpenditure ce,int modify){
        //直接添加modify置为最新的modify,然后保存
        Expenditure e = new Expenditure(ce);
        e.setModify(modify);
        repository.save(e);
    }

    public void removeExpenditure(ClientExpenditure ce){
        //可能删除是在本地离线情况下创建了，又经过了删除 ，先判断是否存在，存在直接在服务器删除，否则不做任何处理
        List<Expenditure> list =  repository.findByUsernameAndYearAndMonthAndDayAndHourAndMinAndSecond(
                ce.getUsername(),ce.getYear(),ce.getMonth(),ce.getDay(),ce.getHour(),ce.getMin(),ce.getSecond());
        if(list.size()==0){
            return;
        }else {
            if(ce.getAnchor() == list.get(0).getModify()) {
                repository.deleteById(list.get(0).getId());
            }
        }
    }

    public List<ClientExpenditure> getUpdateClientExpenditureList(int maxAnchor,String username,int year ,int month){
        //找到大于该用户最大的更新值的数据，同步到客户端
        List<Expenditure> elist = repository.findByModifyGreaterThanAndUsernameAndYearAndMonth(maxAnchor,username,year,month);
        List<ClientExpenditure> celist = new ArrayList<>();
        for(Expenditure i :elist){
            celist.add(new ClientExpenditure(i));
        }
        return celist;
    }

    public int getMaxModify(String username){
        if(repository.getCountOfTable(username)==0){
            return 0;
        }else {
            return (int)repository.getMaxModify(username);
        }
    }
}
